<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function minFallingPathSum(matrix) {
      // 默认最小路径和就是矩阵第一行
      let dp = matrix[0];
      // 从第二行开始，遍历matrix.length-1次
      for (let i = 1; i <= matrix.length - 1; i++) {
        // 记录当前行最小路径和
        const temp = [];
        for (let j = 0; j < matrix.length; j++) {
          // 筛选出合法路径
          const steps = [dp[j - 1], dp[j], dp[j + 1]].filter(Boolean);
          // 取三种路径中最小值
          temp.push(Math.min(...steps) + matrix[i][j]);
        }
        // 保存本轮最小路径和给下次计算使用
        dp = temp;
      }

      return Math.min(...dp);
    };
  </script>
</body>

</html>